package wdsys

import (
	"errors"
	"os"
	"runtime/pprof"
	"time"
)

type pproftype string

var CPU pproftype = "CPU"
var MEM pproftype = "MEM"

//GeneratePprofFile 生成监控文档 监控类型，生成文件路径，多久后开始，开始多久后结束
func GeneratePprofFile(ptype pproftype, path string, start time.Duration, end time.Duration) error {
	if ptype == CPU {
		file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0744)
		if err != nil {
			return err
		}
		go func() {
			<-time.After(start)
			pprof.StartCPUProfile(file)
			<-time.After(end)
			pprof.StopCPUProfile()
		}()
	} else if ptype == MEM {
		file, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0744)
		if err != nil {
			return err
		}
		go func() {
			<-time.After(start)
			pprof.WriteHeapProfile(file)
			<-time.After(end)
		}()
	} else {
		return errors.New("offset one is fail")
	}
	return nil
}
